package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.base.service.impl.BaseServiceImpl;
import com.example.common.enums.ResponseCodeEnum;
import com.example.common.utils.ApiResult;
import com.example.dao.*;
import com.example.model.entity.*;
import com.example.model.query.SuppliesQuery;
import com.example.model.vo.SuppliesVo;
import com.example.service.SuppliesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SuppliesServiceImpl extends BaseServiceImpl<SuppliesMapper, Supplies> implements SuppliesService {


	@Autowired
	private SuppliesMapper suppliesMapper;
	@Autowired
	private SuppliesTypeMapper suppliesTypeMapper;
	@Autowired
	private PersonMapper personMapper;
	@Autowired
	private SuppliesRealinfoMapper suppliesRealinfoMapper;
	@Autowired
	private SuppliesPropMapper suppliesPropMapper;

	@Override
	public ApiResult<SuppliesQuery> pageUserVoByQuery(SuppliesQuery query) {
		query.setOptimizeCountSql(false);
		Long current = query.getCurrent();
		query.setCurrent(1L);
		QueryWrapper<Supplies> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Supplies::getIsValid,1L);
		if(StringUtils.isNotBlank(query.getTypeId())){
			queryWrapper.lambda().eq(Supplies::getTypeId,query.getTypeId());
		}
		Integer total = suppliesMapper.selectCount(queryWrapper);
		query.setTotal(total);
		query.setCurrent(current);
		query.setIsValid(1L);
		suppliesMapper.pageInfoByQuery(query);
		List list = query.getRecords();
		for (int i = 0; i < list.size(); i++) {
			SuppliesQuery suppliesQuery = (SuppliesQuery)list.get(i);
			if(null != suppliesQuery.getTypeId()){
				SuppliesType suppliesType = suppliesTypeMapper.selectById(suppliesQuery.getTypeId());
				if(suppliesType != null && suppliesType.getIsValid() == 1){
					suppliesQuery.setTypeName(suppliesType.getTypeName());
				}
			}
			//得到物资联系人
			QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
			personQueryWrapper.lambda().eq(Person::getSuppliesId,suppliesQuery.getSuppliesId())
					.eq(Person::getIsValid,1L);
			List<Person> personList = personMapper.selectList(personQueryWrapper);
			suppliesQuery.setPersonList(personList);
		}
		return new ApiResult<>(query);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ApiResult<Boolean> saveAd(SuppliesVo suppliesVo) throws Exception {
		QueryWrapper<Supplies> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Supplies::getIsValid,1L)
				.eq(Supplies::getSuppliesNum,suppliesVo.getSuppliesNum());
		int num = suppliesMapper.selectCount(queryWrapper);
		if(num > 0){
			return new ApiResult<>(Boolean.FALSE, ResponseCodeEnum.MALL_SERVICE_SAVE_TYPE_FALSE);
		}
		// 新增
		Supplies supplies = new Supplies();
		BeanUtils.copyProperties(suppliesVo,supplies);
		List<Prop> propList = suppliesVo.getPropList();
		if(propList.size()>0){
			String jsonData = JSONObject.toJSONString(propList);
			supplies.setSuppliesProp(jsonData);
		}
		supplies.setCreateTime(new Date());
		supplies.setUpdateTime(new Date());
		this.save(supplies);
//		List<Person> personList = suppliesVo.getPersonList();
//		for(Person person :personList){
//			person.setSuppliesId(supplies.getSuppliesId());
//			personMapper.insert(person);
//		}
		for(Person person :suppliesVo.getPersonList()){
			person.setSuppliesId(supplies.getSuppliesId());
			personMapper.insert(person);
		}
		return new ApiResult<>(Boolean.TRUE);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ApiResult<Boolean> update(SuppliesVo suppliesVo) throws Exception {
		QueryWrapper<Supplies> suppliesQueryWrapper = new QueryWrapper<>();
		suppliesQueryWrapper.lambda().eq(Supplies::getIsValid,1L)
				.eq(Supplies::getSuppliesNum,suppliesVo.getSuppliesNum())
				.ne(Supplies::getSuppliesId,suppliesVo.getSuppliesId());
		int num = suppliesMapper.selectCount(suppliesQueryWrapper);
		if(num > 0){
			return new ApiResult<>(Boolean.FALSE, ResponseCodeEnum.MALL_SERVICE_SAVE_TYPE_FALSE);
		}
		Supplies supplies = new Supplies();
		BeanUtils.copyProperties(suppliesVo,supplies);
		//删除旧数据
		QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Person::getSuppliesId,supplies.getSuppliesId())
				.eq(Person::getIsValid,1L);
		List<Person> personList = personMapper.selectList(queryWrapper);
		for(Person person : personList){
			person.setIsValid(0L);
			personMapper.updateById(person);
		}
		List<Prop> propList = suppliesVo.getPropList();
		if(propList !=null && propList.size()>0){
			String jsonData = JSONObject.toJSONString(propList);
			supplies.setSuppliesProp(jsonData);
		}
		this.updateById(supplies);
		for(Person person :suppliesVo.getPersonList()){
			person.setPersonId(null);
			person.setSuppliesId(supplies.getSuppliesId());
			personMapper.insert(person);
		}
		//相对应的设备名要同步修改
//		if(StringUtils.isNotBlank(supplies.getReSuppliesId())){
//			Supplies reSupplies = this.getById(supplies.getReSuppliesId());
//			if(reSupplies != null){
//				reSupplies.setSuppliesName(supplies.getSuppliesName());
//				this.updateById(reSupplies);
//			}
//		}
		return new ApiResult<>(Boolean.TRUE);
	}

	@Override
	public ApiResult<SuppliesVo> getInfo(String id) throws Exception{
		Supplies supplies = suppliesMapper.selectById(id);
		SuppliesVo vo = new SuppliesVo();
		BeanUtils.copyProperties(supplies,vo);
		//得到物资联系人
		QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Person::getSuppliesId,id)
				.eq(Person::getIsValid,1L);
		List<Person> personList = personMapper.selectList(queryWrapper);
		vo.setPersonList(personList);
		//得到物资属性
		if(StringUtils.isNotBlank(supplies.getSuppliesProp())){
			List<Prop> propList = JSONObject.parseArray(supplies.getSuppliesProp(),Prop.class);
			vo.setPropList(propList);
		}else {
			List<Prop> propList = new ArrayList<>();
			vo.setPropList(propList);
		}
		//得到物资状态
		QueryWrapper<SuppliesRealinfo> suppliesRealinfoQueryWrapper = new QueryWrapper<>();
		suppliesRealinfoQueryWrapper.lambda().eq(SuppliesRealinfo::getSuppliesId,id)
				.eq(SuppliesRealinfo::getIsNew,1L);
		List<SuppliesRealinfo> suppliesRealinfoList = suppliesRealinfoMapper.selectList(suppliesRealinfoQueryWrapper);
		vo.setSuppliesRealinfoList(suppliesRealinfoList);
		//物资状态数据处理
		QueryWrapper<SuppliesProp> suppliesPropQueryWrapper = new QueryWrapper<>();
		suppliesPropQueryWrapper.lambda().eq(SuppliesProp::getIsValid,1L)
				.eq(SuppliesProp::getTypeId,supplies.getTypeId());
		List<SuppliesProp> propList = suppliesPropMapper.selectList(suppliesPropQueryWrapper);
		String str ="";
		if(propList.size()>0 && suppliesRealinfoList.size()>0){
			SuppliesRealinfo realinfo = suppliesRealinfoList.get(0);
			JSONObject json =JSONObject.parseObject(realinfo.getRealInfo());
			for(SuppliesProp ob : propList){
				String propData = json.getString(ob.getPropLabel());
				if(StringUtils.isNotBlank(propData)){
					String linRead = ob.getPropName()+":"+propData+"\n";
					str = str + linRead;
				}
			}
		}
		vo.setSuppliesRealnfo(str);
		return new ApiResult<>(vo);
	}

	/**
	 * 序列
	 */
	@Override
	public Long seqAlways(){
		return suppliesMapper.seqAlways();
	}

	@Override
	public ApiResult<Boolean> del(String id) throws Exception{
		Supplies supplies = suppliesMapper.selectById(id);
		if(supplies != null){
			supplies.setIsValid(0L);
			suppliesMapper.updateById(supplies);
		}
		return new ApiResult<>(Boolean.TRUE);
	}

	@Override
	public ApiResult<List<Supplies>> getList() {
		QueryWrapper<Supplies> suppliesQueryWrapper = new QueryWrapper<>();
		suppliesQueryWrapper.lambda().eq(Supplies::getIsValid,1L);
		List<Supplies> suppliesList = suppliesMapper.selectList(suppliesQueryWrapper);
		return new ApiResult<>(suppliesList);
	}
}
